package com.sc.VenusQueryBeta.ui.fragments.account.xiaofei;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.listener.DialogUIDateTimeSaveListener;
import com.dou361.dialogui.widget.DateSelectorWheelView;
import com.example.zhouwei.library.CustomPopWindow;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.utils.ResourcesUtils;
import com.hengjun.kingstar.sdk.utils.ScreenUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.PopAdapter;
import com.sc.VenusQueryBeta.adapter.account.xiaofei.XiaoFei01Adapter;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.account.xiaofei.XiaoFei01Contract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.account.CurrencyListBean;
import com.sc.VenusQueryBeta.model.bean.account.xiaofei.XiaoFei01Bean;
import com.sc.VenusQueryBeta.model.bean.login.QueryRegisBean;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.presenter.account.xiaofei.XiaoFei1Presenter;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;

public class XiaoFei01Fragment extends BaseMVPCompatFragment<XiaoFei01Contract.XiaoFei1Presenter> implements XiaoFei01Contract.IXiaoFei1Activity, BaseQuickAdapter.RequestLoadMoreListener {


    private static XiaoFei01Fragment fragment;
    @BindView(R.id.ibtn_xiaofei_back)
    ImageButton ibtnXiaofeiBack;
    @BindView(R.id.vip_user)
    TextView vipUser;
    @BindView(R.id.btn_time)
    Button btnTime;
    @BindView(R.id.vip_uservip_user_infornation)
    RecyclerView vipUservipUserInfornation;
    @BindView(R.id.ptr_class)
    PtrClassicFrameLayout ptrClass;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    Unbinder unbinder;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.tv_all_money)
    TextView tvAllMoney;
    @BindView(R.id.chooise_company)
    TextView chooiseCompany;
    @BindView(R.id.chooise_time)
    TextView chooiseTime;
    @BindView(R.id.header_ll)
    LinearLayout headerLl;
    @BindView(R.id.vp_fragment)
    FrameLayout vpFragment;
    @BindView(R.id.rl_top)
    RelativeLayout rlTop;

    private QueryRegisBean queryRegisBean;
    private int clientindex;
    private String year;
    private String month;
    private int roomid;
    private String time1;
    private String time2;
    private UsersLoginBean loginBean;
    private XiaoFei01Bean xiaoFei01Bean;
    private View headView;
    private TextView tv_jituan;
    private TextView tv_jituan_money;
    private XiaoFei01Adapter xiaoFei01Adapter;
    private String roomname;
    private boolean isUpdate = false;
    private View footView;
    private View errorView;
    private PopAdapter popAdapter;
    private CustomPopWindow mClubPopWindow;
    private RecyclerView clubrecyclerView;
    private CurrencyListBean mallRoomListBean;

    public static XiaoFei01Fragment newInstance(QueryRegisBean queryRegisBean, int clientindex, String roomyear, String roommonth, int roomId, String roomname) {
        Bundle args = new Bundle();
        args.putInt(Constants.CLIENTINDEX, clientindex);
        args.putSerializable(Constants.QUERY_SETTING, queryRegisBean);
        args.putString(Constants.YEAR, roomyear);
        args.putString(Constants.MONTH, roommonth);
        args.putInt(Constants.ROOMID, roomId);
        args.putString(Constants.ROOMNAME, roomname);//这个是币种
        fragment = new XiaoFei01Fragment();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 初始化数据
     */
    @Override
    public void initData() {
        super.initData();
        if (fragment.getArguments() != null) {
            loginBean = SpUtils.getObject(MyApplication.app, UsersLoginBean.class);
            queryRegisBean = (QueryRegisBean) fragment.getArguments().getSerializable(Constants.QUERY_SETTING);
            clientindex = fragment.getArguments().getInt(Constants.CLIENTINDEX, 0);
            roomname = fragment.getArguments().getString(Constants.ROOMNAME);
            year = fragment.getArguments().getString(Constants.YEAR);
            month = fragment.getArguments().getString(Constants.MONTH);
            roomid = fragment.getArguments().getInt(Constants.ROOMID, 0);
            btnTime.setText(year + "/" + month);
        }
    }

    /**
     * 初始化头部
     */
    private void initHeadView() {
        if (headView == null) {
            headView = ResourcesUtils.inflate(R.layout.rv_top_zhuanma01);
        }
        tv_jituan_money = headView.findViewById(R.id.tv_jituan_money);
        if (footView == null) {
            footView = ResourcesUtils.inflate(R.layout.rv_no_more_data);
        }
        if (errorView == null) {
            errorView = ResourcesUtils.inflate(R.layout.view_network_error);
        }
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.getXiaoFei1(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                        getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), month, year, roomname);
            }
        });

    }

    /**
     * 填充數據
     *
     * @param xiaoFei01Bean
     */
    private void initRecycleView(XiaoFei01Bean xiaoFei01Bean) {
        xiaoFei01Adapter = new XiaoFei01Adapter(R.layout.item_xiaofei01_new, xiaoFei01Bean.getList());
        vipUservipUserInfornation.setAdapter(xiaoFei01Adapter);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
            //查询所有厅
//            showProgressDialog("請稍等...");
            mPresenter.queryAllCurrencyList(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort());
        } else {
            ToastUtils.showToast("数据异常");
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return XiaoFei1Presenter.newInstance();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_xiao_fei01_fragment;
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(rlTop.getLayoutParams());

        lp.setMargins(0, ScreenUtils.getStatusBarHeight(mContext)+8, 0, 0);

        rlTop.setLayoutParams(lp);
        //设置币种
        chooiseCompany.setText(roomname);
        //设置时间
        chooiseTime.setText(year + "/" + month);
        initHeadView();
        xiaoFei01Adapter = new XiaoFei01Adapter(R.layout.item_xiaofei01);
        vipUservipUserInfornation.setAdapter(xiaoFei01Adapter);
        vipUservipUserInfornation.setLayoutManager(new LinearLayoutManager(mContext));
        reFreshListener();//下拉刷新
        initClub();//初始化集團佈局

    }

    private void initClub() {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.pop_list, null);
        //处理popWindow 显示内容

        //创建并显示popWindow
        mClubPopWindow = new CustomPopWindow.PopupWindowBuilder(mActivity)
                .setView(contentView)
                .setView(contentView).setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                        lp.alpha = 1f;
                        mActivity.getWindow().setAttributes(lp);
                    }
                })
                .create();
        clubrecyclerView = contentView.findViewById(R.id.recyclerView);


        chooiseCompany.setOnClickListener(new View.OnClickListener() {//选择集团監聽
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    mClubPopWindow.showAsDropDown(chooiseCompany, 40, 0, Gravity.BOTTOM);
                    // 设置背景颜色变暗
                    WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                    lp.alpha = 0.5f;
                    mActivity.getWindow().setAttributes(lp);
                } else {
                    mClubPopWindow.showAsDropDown(chooiseCompany, 40, 0);
                    // 设置背景颜色变暗
                    WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                    lp.alpha = 0.5f;
                    mActivity.getWindow().setAttributes(lp);
                }
            }
        });
        chooiseTime.setOnClickListener(new View.OnClickListener() {//选择年月監聽
            @Override
            public void onClick(View view) {
                chooisTime();
            }
        });
//        tvEmpty.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                start(XiaoFei02Fragment.newInstance(queryRegisBean, clientindex, year, month, 1,chooiseCompany.getText().toString()));
//            }
//        });
    }

    @Override
    public void onLoadMoreRequested() {
        xiaoFei01Adapter.loadMoreComplete();
//        //联网加载更多
        mPresenter.getMoreXiaoFei1(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), month, year, roomname);
    }

    @Override
    public void showNetworkError(Throwable throwable) {
        ToastUtils.showToast(throwable.getMessage());
        xiaoFei01Adapter.setEmptyView(errorView);
        hideProgressDialog();
    }

    @Override
    public void showLoadMoreError() {
        xiaoFei01Adapter.loadMoreFail();
        hideProgressDialog();
    }

    @Override
    public void showNoMoreData() {
        xiaoFei01Adapter.loadMoreEnd(true);
//        xiaoFei01Adapter.setFooterView(footView);
        ToastUtils.showToast("已经加载全部数据了");
        hideProgressDialog();
    }

    @Override
    public void showXiaoFei01Data1Success(final XiaoFei01Bean xiaoFei01Bean) {
//        xiaoFei01Adapter.removeAllHeaderView();
        //設置頭部佈局數據
        tvAllMoney.setText(xiaoFei01Bean.getTotalpriceSum() + " " + getString(R.string.yuan));//設置總額
        //布局处理
        if (xiaoFei01Bean.getList() != null && xiaoFei01Bean.getList().size() > 0) {
            ptrClass.setVisibility(View.VISIBLE);
            tvEmpty.setVisibility(View.GONE);
        } else {
            ptrClass.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.VISIBLE);
        }
        if (xiaoFei01Adapter.getData().size() == 0) {
            initRecycleView(xiaoFei01Bean);
        } else {
            if (isUpdate) {
                isUpdate = false;
                if (xiaoFei01Bean.getList() != null && xiaoFei01Bean.getList().size() > 0) {
                    xiaoFei01Adapter.setNewData(xiaoFei01Bean.getList());
                }
            } else {
                if (xiaoFei01Bean.getList() != null && xiaoFei01Bean.getList().size() > 0) {
                    xiaoFei01Adapter.addData(xiaoFei01Bean.getList());
                }
            }
        }
//        xiaoFei01Adapter.addHeaderView(headView);

        xiaoFei01Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                start(XiaoFei02Fragment.newInstance(queryRegisBean, clientindex, year, month, Integer.parseInt(xiaoFei01Bean.getList().get(position).getRoomid()), chooiseCompany.getText().toString()));
            }
        });
        hideProgressDialog();
        ptrClass.refreshComplete();//
        xiaoFei01Adapter.setOnLoadMoreListener(this, vipUservipUserInfornation);

    }

    @Override
    public void showqueryAllCurrencyList(final CurrencyListBean currencyListBean) {
        if (currencyListBean != null && currencyListBean.getCurrencys().size() > 0) {
//            roomId = Integer.parseInt(currencyListBean.getCurrencys().get(0).getRoomid());
            //填充廳數據
            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
            popAdapter = new PopAdapter(R.layout.pop_list_item, currencyListBean);
            clubrecyclerView.setAdapter(popAdapter);
            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            //集團點擊監聽
            popAdapter.setOnCliCkItemListenerr(new PopAdapter.OnCliCkItemListener() {
                @Override
                public void clickItem(int position) {
//                  roomId = Integer.parseInt(currencyListBean.getRoomList().get(position).getRoomid());
                    chooiseCompany.setText(currencyListBean.getCurrencys().get(position).getCurrencyName1());//動態改變集團名稱
                    isUpdate = true;

                    //查詢最大日期
//                    if (position != 0) {
////                        mPresenter.queryMaxChangemonth(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(), roomId);
//                    } else {
                    if (month.equals("全年")) {
//                    ToastUtils.showToast("全年");
//                    xiaoFeiAdapter.removeAllHeaderView();
                        showProgressDialog("正在加載...");
                        mPresenter.getXiaoFei1(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                                getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), "", year, chooiseCompany.getText().toString());
                    } else {
//                    xiaoFeiAdapter.removeAllHeaderView();
                        showProgressDialog("正在加載...");
                        mPresenter.getXiaoFei1(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                                getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), month, year, chooiseCompany.getText().toString());
                    }
//                    }
                    mClubPopWindow.dissmiss();
                }
            });
            //填充廳數據
            mallRoomListBean = currencyListBean;
//            roomId = allRoomListBean.getRoomList().get(0).getRoomid();//默认第一个厅
//            //查询子户口
            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
                //查询子户口
                showProgressDialog("正在加載...");
                mPresenter.getXiaoFei1(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                        getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), month, year, chooiseCompany.getText().toString());
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hideProgressDialog();
    }

    @OnClick({R.id.ibtn_xiaofei_back, R.id.btn_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_xiaofei_back:
                pop();
                break;
            case R.id.btn_time:
                chooisTime();
                break;
        }
    }

    /**
     * 时间选择
     */
    private void chooisTime() {
        DialogUIUtils.showDatePick(mActivity, Gravity.CENTER, "选择日期", System.currentTimeMillis() + 60000, DateSelectorWheelView.TYPE_YYYYMM, 0, new DialogUIDateTimeSaveListener() {
            @Override
            public void onSaveSelectedDate(int tag, String selectedDate) {//点击年月监听器
                time1 = selectedDate;
                year = selectedDate.substring(0, 4);
                month = selectedDate.substring(selectedDate.length() - 2, selectedDate.length());
                time2 = time1.replace("-", "/");
                chooiseTime.setText(time2);
//                //查询子户口//查询子户口//查询子户口//查询子户口//查询子户口//查询子户口//查询子户口
                isUpdate = true;
                if (month.equals("全年")) {
                    showProgressDialog("加载中...");
                    mPresenter.getXiaoFei1(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                            getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), "", year, chooiseCompany.getText().toString());
                } else {
                    showProgressDialog("加载中...");
                    mPresenter.getXiaoFei1(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                            getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), month, year, chooiseCompany.getText().toString());
                }

            }

        }).show();
    }

    /**
     * 下拉刷新監聽
     */
    private void reFreshListener() {
        MaterialHeader header = new MaterialHeader(mActivity);
        ptrClass.addPtrUIHandler(header);
        ptrClass.setLastUpdateTimeRelateObject(this);//设置刷新支持时间
        ptrClass.setResistance(1.7f);//设置下拉的阻尼系数，值越大感觉越难下拉
        ptrClass.setDurationToCloseHeader(1000);//设置刷新完成，头部回弹时间，注意和前一个进行区别
        ptrClass.setPullToRefresh(false);//设置下拉过程中执行刷新，我们一般设置为false
        ptrClass.setKeepHeaderWhenRefresh(true);//设置刷新的时候是否保持头部
        ptrClass.setPtrHandler(new PtrDefaultHandler() {               //下拉刷新
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //模拟联网，延迟更新数据
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mPresenter != null&&ptrClass!=null&&chooiseCompany!=null) {
                            isUpdate = true;
                            showProgressDialog("加载中...");
                            mPresenter.getXiaoFei1(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                                    getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), month, year, chooiseCompany.getText().toString());
                        }

                        if (ptrClass == null) {
                            hideProgressDialog();
                        }
                    }
                }, 1000);
            }
        });
    }
}
